/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package testAgent.behaviours.equation;

import jade.core.behaviours.Behaviour;
import jade.core.behaviours.DataStore;
import jade.core.behaviours.OneShotBehaviour;
import jade.core.behaviours.SequentialBehaviour;
import testAgent.behaviours.equation.simpleBehaviours.IncrementExponentBehaviours;
import testAgent.behaviours.equation.simpleBehaviours.MultiplyCoefficientBehaviours;
import testAgent.behaviours.responder.EquationSolverResponderBehaviours;
import udes.ds.agent.BasicEquation;

/**
 * 
 * @author Cody Stoutenburg
 * 
 */
public class SolveBasicEquationBehaviours extends SequentialBehaviour {

	private static final long serialVersionUID = 1478302233303356503L;

	private static final String START_EQUATION = "equation";
	private static final String FINISH_EQUATION = "result";

	private final String resultKey;
	private final DataStore sharedDatastore;

	public SolveBasicEquationBehaviours(BasicEquation equation, String resultKey) {
		super();

		this.resultKey = resultKey;

		this.addSubBehaviour(new IncrementExponentBehaviours(START_EQUATION,
				START_EQUATION, -1));
		this.addSubBehaviour(new MultiplyCoefficientBehaviours(START_EQUATION,
				FINISH_EQUATION, equation.getExponent()));
		this.addSubBehaviour(new solveBehaviours());

		sharedDatastore = getDataStore();
		sharedDatastore.put(START_EQUATION, equation);

		for (Object behaviour : this.getChildren().toArray()) {
			((Behaviour) behaviour).setDataStore(sharedDatastore);
		}
	}

	private void finishSolveEquation() {
		getDataStore().put(resultKey, sharedDatastore.get(FINISH_EQUATION));
		getDataStore().put(EquationSolverResponderBehaviours.IS_CALCUL_FINISH,
				0);
	}

	private class solveBehaviours extends OneShotBehaviour {

		private static final long serialVersionUID = -2770911657283715286L;

		@Override
		public void action() {
			finishSolveEquation();
		}
	}
}
